from rest_framework_jwt.views import JSONWebTokenAPIView
from rest_framework_jwt.settings import api_settings
from rest_framework import status
from rest_framework.response import Response
from .APISerializers import APILoginSerializer
from core.tools.custom_views import CustomJSONWebTokenAPIView, get_exception
jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER


# 注册登录
class LoginRegisterViewSet(CustomJSONWebTokenAPIView):
    serializer_class = APILoginSerializer

    # @get_exception()
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            serializer.save()
            token = serializer.object.get('token')
            code = 200
            message = "OK"
            expiration = int(api_settings.JWT_EXPIRATION_DELTA.days * 3600)
            content = {"code": code, "message": message, "result": {
                "token": token, "expires": expiration
            }}
            response = Response(content)
            return response
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
